import sys
import pytz
from datetime import datetime
from queue import Queue
from database import db as mongo
from utils import create_papers, show_group_chat, notify_user, create_papers_highlight, create_papers_classification, create_papers_republic
from fetch_todaypapers2mongo import crawl_arxiv_daliy
from recommend import recommendation_ranking, select_paper_by_probability, recommend_addup, recommendation_highlight, article_republish

from config import config


def fetchAndClass(receiver:list=None):
    today = datetime.strptime(datetime.now().astimezone(pytz.timezone('Asia/Shanghai')).strftime("%Y-%m-%d"), "%Y-%m-%d")
    doc = mongo.document.find_one({'createDate': today})
    if not doc is None:
        jsonObjects = [
            [
                {
                    "tag": "a",
                    "href": doc['docNo'],
                    "text": doc['docTitle']
                }
            ]
        ]
        for chat in receiver:
            if chat.startswith('oc'):
                notify_user(chat, jsonObjects, config, receiver='chat_id')
            else:
                notify_user(chat, jsonObjects, config)
        return
    data = crawl_arxiv_daliy()
    reccommend, appearIncrease, class_list = recommendation_highlight(data)
    for i in range(len(reccommend)):
        recommend_addup(reccommend[i], appearIncrease[i], appearIncrease[i], len(data))
    for (key, value) in class_list.items():
        value.sort(key=lambda sum: sum['score'])
        class_list[key] = value[::-1]
    if receiver is None:
        openId = show_group_chat(config)
        info = create_papers_classification(openId, class_list, config, receiver="chat_id", today=today, user=mongo.user.find({'subscribe': True}))
    else:
        info = create_papers_classification(receiver, class_list, config, today=today)
    if not info is None:
        mongo.create_document(*info, createDate=today)


def republish_recommend(receiver:list=None):
    today = datetime.strptime(datetime.now().astimezone(pytz.timezone('Asia/Shanghai')).strftime("%Y-%m-%d"), "%Y-%m-%d")
    doc = mongo.document.find_one({'createDate': today})
    if not doc is None:
        jsonObjects = [
            [
                {
                    "tag": "a",
                    "href": doc['docNo'],
                    "text": doc['docTitle']
                }
            ]
        ]
        for chat in receiver:
            if chat.startswith('oc'):
                notify_user(chat, jsonObjects, config, receiver='chat_id')
            else:
                notify_user(chat, jsonObjects, config)
        return
    data = article_republish()
    doc_list = mongo.document_link()
    reccommend, appearIncrease, _ = recommendation_highlight(data)
    if receiver is None:
        openId = show_group_chat(config)
        info = create_papers_republic(openId, data, doc_list, config, receiver="chat_id", today=today, user=mongo.user.find({'subscribe': True}))
    else:
        info = create_papers_republic(receiver, data, doc_list, config, today=today)
    if not info is None:
        mongo.create_document(*info, createDate=today)
    mongo.article_expire()


def fetchAndCast(receiver:list=None):
    today = datetime.strptime(datetime.now().astimezone(pytz.timezone('Asia/Shanghai')).strftime("%Y-%m-%d"), "%Y-%m-%d")
    doc = mongo.document.find_one({'createDate': today})
    if not doc is None:
        jsonObjects = [
            [
                {
                    "tag": "a",
                    "href": doc['docNo'],
                    "text": doc['docTitle']
                }
            ]
        ]
        for chat in receiver:
            if chat.startswith('oc'):
                notify_user(chat, jsonObjects, config, receiver='chat_id')
            else:
                notify_user(chat, jsonObjects, config)
        return
    data = crawl_arxiv_daliy()
    reccommend, appearIncrease, _ = recommendation_highlight(data)
    for i in range(len(reccommend)):
        recommend_addup(reccommend[i], appearIncrease[i], appearIncrease[i], len(data))
    data.sort(key=lambda sum: sum['score'])
    data = data[::-1]
    if receiver is None:
        openId = show_group_chat(config)
        info = create_papers_highlight(openId, data, config, receiver="chat_id", today=today, user=mongo.user.find({'subscribe': True}))
    else:
        info = create_papers_highlight(receiver, data, config, today=today)
    if not info is None:
        mongo.create_document(*info, createDate=today)


def fetchAndRecommend(receiver:list=None):
    today = datetime.strptime(datetime.now().astimezone(pytz.timezone('Asia/Shanghai')).strftime("%Y-%m-%d"), "%Y-%m-%d")
    doc = mongo.document.find_one({'createDate': today})
    if not doc is None:
        jsonObjects = [
            [
                {
                    "tag": "a",
                    "href": doc['docNo'],
                    "text": doc['docTitle']
                }
            ]
        ]
        for chat in receiver:
            if chat.startswith('oc'):
                notify_user(chat, jsonObjects, config, receiver='chat_id')
            else:
                notify_user(chat, jsonObjects, config)
        return
    data = crawl_arxiv_daliy()
    length = len(data)
    reccommend, appearIncrease = recommendation_ranking(data)
    recommendUpdate = [0]*len(reccommend)
    data.sort(key=lambda sum: sum['score'])
    selected = Queue(10)
    for i in range(9, -1, -1):
        selected.put(data[i])
    for i in range(len(data)-1, -1, -1):
        if select_paper_by_probability(data[i]['probability']):
            selected.get()
            selected.put(data[i])
    for i in list(selected.queue):
        for j in i['recommendUpdate']:
            recommendUpdate[j] += 1
    for i in range(len(reccommend)):
        recommend_addup(reccommend[i], appearIncrease[i], recommendUpdate[i], length)
    selected = list(reversed(list(selected.queue)))
    if receiver is None:
        openId = show_group_chat(config)
        info = create_papers(openId, selected, config, receiver="chat_id", today=today)
    else:
        info = create_papers(receiver, selected, config, today=today)
    if not info is None:
        for a in selected:
            mongo.article.update_one({'rawId': a['rawId']}, {'$set': {'recommend': today}})
        mongo.create_document(*info, createDate=today)

# python /home/cchang/arXivPost/daliy_task.py ou_7fd3ab84d15e9d3e6f95e475bc7ea76b ou_7fd3ab84d15e9d3e6f95e475bc7ea76b
if __name__ == '__main__':
    if len(sys.argv) > 1:
        if sys.argv[1] == "republish_recommend":
            if len(sys.argv) > 2:
                republish_recommend(sys.argv[2:])
        else:
            fetchAndClass(sys.argv[1:])
    else:
        fetchAndClass(["ou_7fd3ab84d15e9d3e6f95e475bc7ea76b"])
